package com.dime.interceptor;

import com.dime.Constants.MNRequestHeadConstants;
import com.dime.utils.MNStringUtils;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.api.model.UserShop;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Optional;

@Component
public class MNFeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        if (StringUtils.isNotNull(httpServletRequest)) {
            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
            String shopCode = SecurityUtils.getShopId();
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if(StringUtils.isNotNull(loginUser) && StringUtils.isNotNull(shopCode) && StringUtils.isNotNull(loginUser.getShops())){
                for (UserShop userShop:loginUser.getShops()) {
                    if(userShop.getShopCode().equals(shopCode)) {
                        String mnappid = userShop.getMnappid();
                        String mnsecret = userShop.getSecret();
                        long timestamp = MNStringUtils.getMNTimestamp();
                        requestTemplate.header(MNRequestHeadConstants.MN_APPID, mnappid);
                        requestTemplate.header(MNRequestHeadConstants.MN_TIMESTAMP, "" + timestamp);
                        requestTemplate.header(MNRequestHeadConstants.MN_SIGN, MNStringUtils.getMNSign(mnappid, mnsecret, timestamp));
                        break;
                    }
                }
            }
            requestTemplate.header(MNRequestHeadConstants.CONTENT_TYPE, MNRequestHeadConstants.CONTENT_TYPE_Value);
            // 配置客户端IP
            requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr());
        }
    }
}
